<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>Spring Boot+WebSocket</title>

</head>
<body onload="disconnect()">
<noscript><h2 style="color: #ff0000">貌似你的浏览器不支持websocket</h2></noscript>
<div>
    <div>
        <button id="connect" onclick="connect();">连接</button>
        <button id="disconnect" disabled="disabled" onclick="disconnect();">断开连接</button>
    </div>
    <div id="conversationDiv">
        <label>输入你的名字</label><input type="text" id="name" />
        <button id="sendName" onclick="sendName();">发送</button>
        <p id="response"></p>
    </div>
</div>
<script src="./sockjs.js"></script>
<script src="./stomp.js"></script>
<script src="./jquery.js"></script>
<script type="text/javascript">
    var stompClient = null;

    function setConnected(connected) {
        document.getElementById('connect').disabled = connected;
        document.getElementById('disconnect').disabled = !connected;
        document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
        $('#response').html();
    }
	
    function connect() {
       //若前后端分离,url要写全，若在一个项目内，只写/websocket/server就行
        //var url = "http://localhost:8866/myws/websocket?user=Jack"
        //var socket = new SockJS(url); //链接SockJS 的endpoint 名称为后台声明的"/websocket/server"
        //stompClient = Stomp.over(socket);//使用stomp子协议的WebSocket 客户端
		stompClient = Stomp.client('ws://localhost:8866/myws/websocket?user=001');
        stompClient.connect({name: '001'}, function(frame) {//链接Web Socket的服务端。
            setConnected(true);
            console.log('Connected: ' + frame);
            //广播式发送，订阅地址不需要加唯一标识；点对点发送，可自定义唯一标识
            var subUrl= '/user/queue/reply';
            //var subUrl= '/topic/notice';
            stompClient.subscribe(subUrl, function(respnose){ //订阅/topic/response 目标发送的消息。这个是在控制器的@SendTo中定义的。
                showResponse(respnose.body);
            });
        });
    }
	
	
    function disconnect() {
        if (stompClient != null) stompClient.disconnect();
        setConnected(false);
        console.log("---------- Disconnected ----------");
    }

    function sendName() {
        var name = $('#name').val();
   		//通过stompClient.send 向/welcome 目标 发送消息,这个是在控制器的@messageMapping 中定义的。
   		//在这里，可根据业务自定义json，甚至可以把订阅地址的唯一标识在此传入给后台解析
        //stompClient.send("/message/zxcv", {}, JSON.stringify({ 'name': name }));
        stompClient.send("/message/chat.002", {to: "002"}, JSON.stringify({ 'name': name }));
    }

    function showResponse(message) {
          var response = $("#response");
          response.html(message);
    }
</script>
</body>
</html>
